package com.mydb.json;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import net.sf.json.JSONObject;

public class JsonHandler {

	public static JsonHandler jsonHandler;
	
	private JsonHandler() {
		
	}
	
	public static JsonHandler getInstance() {
		if(jsonHandler == null) {
			jsonHandler = new JsonHandler();
		}
		return jsonHandler;
	}
	
	public String format(Map data) {
		JSONObject json = new JSONObject();
		
		Iterator<Entry> i = data.entrySet().iterator();
		while(i.hasNext()) {
			Entry entry = i.next(); 
			String key = (String)entry.getKey();
			String value = (String)entry.getValue();
			json.put(key, value);
		}
		
		return json.toString();
	}
	
	public boolean containsKey(String data, Map cond) {
		boolean isExist = false;
		JSONObject json = JSONObject.fromObject(data);
		Iterator<Entry> i = cond.entrySet().iterator();
		while(i.hasNext()) {
			Entry entry = i.next(); 
			String key = (String)entry.getKey();
			String value = (String)entry.getValue();
			String temp = (String)json.get(key);
			if(value.equals(temp)) {
				isExist = true;
			} else {
				isExist = false;
			}
		}
		return isExist;
	}
	
	public String setJsonData(String data, Map updateMap) {
		JSONObject json = JSONObject.fromObject(data);
		json.putAll(updateMap);
		return json.toString();
	}
	
	public Map getDataFromJson(String data) {
		Map map = new HashMap();
		JSONObject json = JSONObject.fromObject(data);
		Iterator i = json.keys();
		while(i.hasNext()) {
			Object key = i.next();
			if(key != null){
				map.put(key.toString(), json.get(key));
			}
		}
		return map;
	}
	
	public static void main(String[] args) {
		JsonHandler json = JsonHandler.getInstance();
		Map map1 = new HashMap();
		map1.put("id", "123");
		map1.put("name", "qwer");
		String str1 = json.format(map1);
		System.out.println(str1);
		Map map2 = new HashMap();
		map2.put("id", "456");
		map2.put("name", "asdf");
		String str2 = json.setJsonData(str1, map2);
		System.out.println(str2);
	}

}
